package com.dries.security.browser.authorize;

import cn.hutool.core.util.StrUtil;
import com.dries.security.core.authorize.AuthorizeConfigProvider;
import com.dries.security.core.properties.SecurityCoreProperties;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Description: 浏览器环境默认的授权配置，对常见的静态资源，如js,css，图片等不验证身份
 * @Author ZSY
 * @createTime 2020/9/20 14:04
 */
@Component
@Order(Integer.MIN_VALUE)
public class BrowserAuthorizeConfigProvider implements AuthorizeConfigProvider {

    @Resource
    public SecurityCoreProperties coreProperties;

    /**
     * @param config
     * @return 返回的boolean表示配置中是否有针对anyRequest的配置。在整个授权配置中，
     * 应该有且仅有一个针对anyRequest的配置，如果所有的实现都没有针对anyRequest的配置，
     * 系统会自动增加一个anyRequest().authenticated()的配置。如果有多个针对anyRequest
     * 的配置，则会抛出异常。
     */
    @Override
    public boolean config(ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry config) {

        config.antMatchers(
//                HttpMethod.GET,
                "swagger-ui.html",
                "/swagger-resources/**",
                "/swagger/**",
                "/**/*.js",
                "/**/*.css",
                "/**/*.jpg",
                "/**/*.png",
                "/**/*.gif",
                "/druid/**",
                "/actuator/**",
                coreProperties.getBrowser().getLoginPage(),
                coreProperties.getBrowser().getRegisterPage(),
                coreProperties.getBrowser().getSession().getSessionInvalidUrl()
                ).permitAll();

        if (StrUtil.isNotBlank(coreProperties.getBrowser().getLogoutPage())) {
            config.antMatchers(coreProperties.getBrowser().getLogoutPage()).permitAll();
        }

        return false;
    }
}
